#!/usr/bin/python
# -*- coding: utf-8 -*-
#Python Es la Riata.com
#Fecha: 29/noviembre/2011
#R.A.P.S
import sys, os             
pathname = os.path.dirname(sys.argv[0])        
ruta=pathname.split("/src")
Exacto=os.path.abspath(ruta[0])
try:
	import gtk
	from reproductor import *
	from NuevaLista import *
	import time 
	import gobject
	
except ImportError:
    sys.exit("pygtk not found.")
	
class listilla:
	def __init__(self,parent,xmms):
		
		self.parent = parent
		self.builder = gtk.Builder()
		UI_FILE=Exacto+"/data/lista.ui"
		self.builder.add_from_file(UI_FILE)
		self.ratero = self.builder.get_object("lista")
		self.entry1 = self.builder.get_object("entry1")
		self.treeview1 = self.builder.get_object("treeview1")
		self.mas= self.builder.get_object("mas")
		self.menos = self.builder.get_object("menos")
		self.kulillo = self.builder.get_object("kulillo")
		self.nuevo = self.builder.get_object("nuevo")
		self.keygo = self.builder.get_object("label8")
		self.lactual = self.builder.get_object("lactual")

		self.xmms = xmms
		self.changej="OFF"
		self.xmms.playback_current_id(self.handler_playback_current_id)
		self.xmms.playlist_list_entries('_active', self.get_tracks)
		self.xmms.broadcast_playback_current_id(self.handler_playback_current_id)
		self.xmms.broadcast_playlist_changed(self.Update)
		self.xmms.playlist_current_active(self.geet)
		
		
		self.modelo = gtk.ListStore (int,str, 'gboolean')
		if self.changej=="OFF":
			self.treeview1.set_model(self.modelo)
		render = gtk.CellRendererText() 
		render.set_property('cell-background', '#EFF5FB')
		columna = gtk.TreeViewColumn ("Lista de Reproduccion",render,text=1,cell_background_set=2)
		self.treeview1.append_column(columna)	
		self.fondo = True
		self.builder.connect_signals(self)
	  
		self.pistaActual = ""
		self.duracion= 0
		self.modelControl=True
		self.Imcon= True
		self.E=""
		
		
####Nombre de la Lista Actual###################################################

	def geet(self,result):
		nombre=result.value()
		self.keygo.set_text(nombre)
		#self.lactual.set_text(nombre)
		return nombre
		
	def Epist (self, widget, *event):
		#self.treeview1.set_model(self.modelo)
		self.getPos ("Eliminar",GetPo=None)

	def OpnList (self, widget, *event):
		self.Nlist = libreria(self,self.xmms)
		self.Nlist.ventanilla.show()

	def wujo(self,result):
		net = result.value()
				
	def  Google (self, position):
		try:
			if self.changej=="OFF":
				self.modelo.remove(self.modelo[position].iter)
			else:
				self.modelo.remove(self.modelo[position].iter)
				self.buscar(self)
		except:
				self.error ("Error Al Remover la Pista " ,300,170)

##############Ventana de *ERROR* ###############################################################

	def error(self, message,x,y):
		"Dialogo de Error"
		dialog_error = gtk.MessageDialog(parent=None, flags=0,buttons=gtk.BUTTONS_OK)
		dialog_error.set_title("Guaky Dice:")
		dialog_error.set_size_request(x,y)
		label = gtk.Label(message)
		dialog_error.vbox.pack_start(label, True, True, 0)
		dialog_error.show_all()
		dialog_error.run()
		dialog_error.destroy()
		

	def get_tracks(self, result):
		playlist = result.value()
		for element in playlist:
			self.xmms.medialib_get_info(element, self.add_track)
		
	def add_track(self, result):
		taginfo = self.get_taginfo(result.value())
		if taginfo[6]!="No disponible":
			self.modelo.append([taginfo[0], "%s - %s" % (taginfo[1], taginfo[2]), self.fondo])
			self.fondo= (True, False)[self.fondo==True]
		else:
			if self.Imcon==False:
				self.error("Algunos de los Archivos contenidos en el directorio no son Compatibles",500,170)
				self.Imcon= True

	def fucLimp(self):
		self.modelo.clear()
		self.xmms.playlist_list_entries('_active', self.get_tracks)

	def handler_playback_current_id(self, result):
		kop=result.value()
		self.xmms.medialib_get_info(result.value(), self.set_track_player)
		
	def set_track_player(self, result):
			try:
				track = self.get_taginfo(result.value())
				self.pistaActual = "%s - %s" % (track[1],track[2])	
				self.duracion = result.value()['duration']
				if self.parent.hok==True:
					self.parent.window.set_title("%s" % (track[2]))
					self.ratero.set_title("Lista de Reproducción")
			except:			
				pass

	def destruir(self, result):
		self.parent.pick=False
		self.changej="OFF"

########Informacion ######################################################################################################

	def get_taginfo(self, info):
				track=[]
				track.append(info['id'])
			
				if info.has_key('artist'):
					track.append(info["artist"])
				else:
					track.append("No disponible")
				if info.has_key('title'):
					track.append(info["title"])
				else:
					track.append("No disponible")
				if info.has_key('album'):
					track.append(info["album"])
				else:
					track.append("No disponible")
				if info.has_key('genre'):
					track.append(info["genre"])
				else:
					track.append("No disponible")
				if info.has_key('picture_front'):
					track.append(info["picture_front"])
				else:
					track.append("No disponible")
				if info.has_key('mime'):
					track.append(info["mime"])
				else:
					track.append("No disponible")

					
				return track
				
	def vasilisko (self, widget, event):				
		if event.keyval	in [65361]:
			self.getPos("Informacion",GetPo=None)
			
	def Kale (self, result):
		try:
			if result.value()!='Could not retrieve info for that entry':
				taginfo = self.get_taginfo(result.value())
				self.parent.imfomeshion(taginfo[2],taginfo[3],taginfo[1],taginfo[4],taginfo[5])
				self.E=""
			else:
				self.error ("No Es una Pista",220,170)
		except:
			self.error ("No Es una Pista",220,170)
			self.E="OK"
			
	def getPos (self, orden,GetPo):
		try:
			if GetPo==None:
				(modelo,iter)=self.treeview1.get_selection().get_selected()
				if iter != None:
					gawek=list(modelo[iter])
					if  self.changej=="OFF":
						elemento=self.modelo.get_value(iter, 0)
					else:
						elemento=int(gawek[0])
						if orden=="Eliminar":
							self.modeltemp.remove(iter)
			else:
				elemento=GetPo
			if  orden=="Informacion":
				self.xmms.medialib_get_info(elemento, self.Kale)
			else:
				det=0
				if elemento> -1:
					for parametro in self.modelo:
						if parametro[0] ==elemento:		
							elemento=det
						det=det+1
					if orden=="Eliminar" and self.changej=="OFF":
						self.modelo.remove(iter)
					if orden=="Eliminar":
						self.xmms.playlist_remove_entry(elemento)
					if orden=="Play":
						self.play_det(elemento)
		except:
				self.error("Selecciona primero",270,150)
		
					
	def play_det(self,pos):
		if self.E!="OK":
			self.xmms.playback_start()
			self.xmms.playlist_set_next(pos)
			self.xmms.playback_tickle()

	def chingatela (self, widget, *event):
		self.treeview1.set_model(self.modelo)
		self.xmms.playlist_clear()

	def on_treeview1_row_activated(self, widget ,iter, path):
		modelo = widget.get_model()
		GetPo = int(modelo.get_value(modelo[iter[0]].iter, 0))
		if GetPo=="":
			print "No es una Pista"
		else:
			self.getPos ("Play",GetPo)
			self.getPos ("Informacion",GetPo)
		
		
########Dialogo de Seleccion de Pista #########################################################

	def seleccione (self, widget,*event):
		
		self.modelControl=False
		cucaracha = gtk.FileChooserDialog(title="Seleccion de Pistas a Importar",action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))

		cucaracha.set_current_folder("home")
		cucaracha.set_select_multiple(True)
		filter = gtk.FileFilter()
		filter.set_name("Archivos de Musica")
		filter.add_pattern("*.mp3")
		filter.add_pattern("*.flac")
		filter.add_pattern("*.wav")
		filter.add_pattern("*.ogg")
		filter.add_pattern("*.m4a")
		filter.add_pattern("*.ogm")
		filter.add_pattern("*.aac")
		filter.add_pattern("*.ogg")
		
		cucaracha.add_filter(filter)

		response = cucaracha.run()

		if response == gtk.RESPONSE_OK:
			for urlRolax in cucaracha.get_filenames():
				self.xmms.playlist_add_url('file://%s' %  urlRolax )
				
		elif response == gtk.RESPONSE_CANCEL:
			print 'No selecciono pistas'
		cucaracha.destroy()

	def Update(self, result):		
			update = result.value()
			if update['type']==0: 
				if self.modelControl==False:
					self.modelControl=True
					self.Actualizacion()
			elif update['type']==1:
				self.xmms.medialib_get_info(update['id'], self.add_track)
			elif update['type']==2:
				self.model_songs.clear()
				self.xmms.playlist_list_entries('_active', self.get_tracks)
			elif update['type']==3:
				if self.changej=="ON":
					self.Google(update['position'])
			elif update['type']==4:
				self.modelo.clear()
				if self.changej=="ON":
					self.modeltemp.clear()
			elif update['type']==5:
				try:
					self.modelo.swap(self.modelo[update['position']].iter, self.modelo[update['newposition']].iter)
				except:
					pass
			elif update['type']==7:
					self.modelo.clear()
					self.keygo.set_text(update['name'])

	def Actualizacion(self):
		time.sleep(0.600)
		#self.pick=False
		#self.parent.listagot(0)
		self.modelo.clear()
		self.xmms.playlist_list_entries('_active', self.get_tracks)
					
	def buscar(self, widget):
		busqueda=self.entry1.get_text()
		if busqueda=="":
			self.treeview1.set_model(self.modelo)
			self.changej="OFF"
		else:
			self.changej="ON"
			self.check=False
			match=""
			self.modeltemp = gtk.ListStore (int, str,'gboolean')
			fondo = True
			for i in self.modelo:						
				match = re.search(busqueda.lower(), self.modelo.get_value(i.iter, 1).lower())
				if match:
					self.modeltemp.append([self.modelo.get_value(i.iter, 0), self.modelo.get_value(i.iter, 1),fondo])
					fondo = (True, False)[fondo==True]
					self.check=True
			if not match:
				if self.check!=True:
					nai="No se Encontraron Pistas"
					self.modeltemp.append([-1,nai,self.fondo])
					self.NFound="1"
					self.check=True
			self.treeview1.set_model(self.modeltemp)
			
	def cb(self,widget, drag_context, x, y, selection,info,time):
		self.treeview1.set_model(self.modelo)
		try:
			drop_info =self.treeview1.get_dest_row_at_pos(x,y)
		except:
				pass
		if drop_info:
			path, position = drop_info
			inicio = selection.data
			self.p1=int(inicio[4])
			self.p2=int(path[0])
			
	def cb1(self,widget, drag_context):
		self.entry1.set_text("")
		try:
			self.xmms.playlist_move(self.p1,self.p2)
		except:
			pass
		self.modelo.clear()
		self.xmms.playlist_list_entries('_active', self.get_tracks)

		###Seleccion recursiva##############################################################
	
	def SReco (self, widget,*event):
		self.changej="OFF"
		self.treeview1.set_model(self.modelo)		
		self.modelControl=False
		self.Imcon= False
		cucaracha = gtk.FileChooserDialog(title="Seleccion de Pistas a Importar",action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
	
		cucaracha.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
		cucaracha.set_select_multiple(True)
		response = cucaracha.run()

		if response == gtk.RESPONSE_OK:
			for urlRolax in cucaracha.get_filenames():
				self.xmms.playlist_radd('file://%s' %  urlRolax)
				
				
				#self.xmms.playlist_list_entries('_active', self.get_tracks)
		elif response == gtk.RESPONSE_CANCEL:
			print 'No selecciono pistas'
		cucaracha.destroy()

	def onLi (self, widget,*event):
		self.parent.Loadlist(0,0)
		
################Guaky-mp3 y Xmms2  5/Nov/2011##################################################
